﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FSMSystem
{
    private Dictionary<EFSMState,IFSMState> m_PlayerStates; 
    public IFSMState CurrentState { get; private set; }
    public FSMSystem()
    {
        m_PlayerStates = new Dictionary<EFSMState, IFSMState>();
    }
    public void AddState(IFSMState _state)
    {
        IFSMState _tmpState = GetState(_state.GetState());
        if (_tmpState == null)
        {
            m_PlayerStates.Add(_state.GetState(),_state);
        }
        else
        {
            Debug.LogWarningFormat("FSMSystem is exist: {0}", _state.GetState().ToString());
        }
    }
    public void RemoveState(IFSMState _state) 
    {
        IFSMState _tmpState = GetState(_state.GetState());
        if (_tmpState != null)
        {
            m_PlayerStates.Remove(_tmpState.GetState());
        }
        else
        {
            Debug.LogWarningFormat("FSMSystem is exist state : {0}", _state.GetState().ToString());
        }
    }
    public IFSMState GetState(EFSMState state)
    {
        if(m_PlayerStates.TryGetValue(state, out IFSMState playerState))
        {
            return playerState;
        }

        return null;
    }

    public bool  IsCanChangeState()
    {
        //TODO check conditions
        return true;
    }
   
    public void ChangeState(EFSMState state)
    {
        if(false == IsCanChangeState())
        {
            return;
        }
        IFSMState _tmpState = GetState(state);  
        if (_tmpState == null)
        {
            Debug.LogWarningFormat("FSMSystem is exist state : {0}", state.ToString());
            return;
        }
        if (CurrentState != null) 
        {
            CurrentState.Leave();
        }
        CurrentState = _tmpState; 
        CurrentState.Enter();  
    }

    public void Update()
    {
        if (CurrentState != null)
        {
            CurrentState.Update();
        }
    }

    public void RemoveAllState() 
    {
        if (CurrentState != null)
        {
            CurrentState.Leave();
            CurrentState = null;
        }
        m_PlayerStates.Clear();
    }
}